import React, { useRef, useEffect, useState } from 'react';
import FilePicker from '@/components/file-picker';
import { ImageUploader, Space, Toast, Dialog } from 'antd-mobile';
import { FileItem } from 'antd-mobile/es/components/image-uploader';


const UploadPic = (props) => {
  const { onChange, value } = props;
  const action = props.action || '/action/upload';
  const handleChange = (val) => {
    console.log('val-------{}', val);
    onChange && onChange(val);
  };


  const [fileList, setFileList] = useState<FileItem[]>([
    {
      url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    }
  ]);

  const send = (url: string, file: File) => {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      const formData = new FormData();
      xhr.open('POST', url);
      formData.append('file', file);
      xhr.send(formData);
      xhr.onload = () => {
        if (xhr.readyState === 4) {
          console.log('xhr.responseText',xhr.responseText);
          
          const data = JSON.parse(xhr.responseText);
          resolve(data);
        }
      };
      xhr.onerror = (e) => {
        reject(e);
      };
    });
  };

  const mockUpload = (e) => {
    return new Promise<FileItem>((resolve,reject) => {
      send(action, e).then((data) => {
        resolve({
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
        });
      }).catch((e) => {
        reject(e);
      });
    });
  };

  return (
    <ImageUploader
      value={fileList}
      onChange={setFileList}
      upload={mockUpload}
    />
  );
};

export default UploadPic;
